<template>
  <div class="register-container">
    <el-form
        :model="registerForm"
        :rules="rules"
    ref="registerForm"
    class="register-form"
    >
    <h2>注册</h2>
    <el-form-item label="用户名" prop="username"> <!-- 添加 prop 属性 -->
      <el-input v-model="registerForm.username" autocomplete="off" class="input-field" />
    </el-form-item>
    <el-form-item label="密码" prop="password"> <!-- 添加 prop 属性 -->
      <el-input v-model="registerForm.password" autocomplete="off" type="password" class="input-field" />
    </el-form-item>
    <el-form-item label="邮箱" prop="emailPrefix"> <!-- 添加 prop 属性 -->
      <el-input v-model="registerForm.emailPrefix" autocomplete="off" class="input-field">
        <template #append>
          <span>@163.com</span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="验证码">
      <div class="verification-container">
        <el-input
            v-model="registerForm.verificationCode"
            autocomplete="off"
            class="verification-input input-field"
        />
        <el-button
            :disabled="isButtonDisabled"
            @click="sendVerificationCode"
            class="send-code-button"
        >
          <el-icon><Message /></el-icon>
          {{ isButtonDisabled ? countdown + '秒后可重发' : '发送验证码' }}
        </el-button>
      </div>
    </el-form-item>
    <el-form-item class="button-row">
      <el-button type="primary" @click="onSubmit" class="register-button">
        <el-icon><UserFilled /></el-icon> 注册
      </el-button>
      <el-button @click="goToLogin" class="login-button">
        <el-icon><Back /></el-icon> 登录
      </el-button>
    </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { Message, UserFilled, Back } from '@element-plus/icons-vue';

export default {
  name: 'Register',
  components: {
    UserFilled,
    Message,
    Back
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      const emailPattern = /^[a-zA-Z0-9_.+-]+$/;
      if (!value) {
        callback(new Error('请输入邮箱'));
      } else if (!emailPattern.test(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      } else {
        callback();
      }
    };

    return {
      registerForm: {
        username: '',
        password: '',
        emailPrefix: '',
        verificationCode: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度在 3 到 15 个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
        ],
        emailPrefix: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      countdown: 60,
      isButtonDisabled: false
    };
  },
  methods: {
    async sendVerificationCode() {
      // 检查邮箱是否为空
      if (!this.registerForm.emailPrefix) {
        ElMessage.error('请输入邮箱');
        return;
      }

      if (!this.isButtonDisabled) {
        const fullEmail = `${this.registerForm.emailPrefix}@163.com`;
        axios.post(`/user/sendCode?email=${encodeURIComponent(fullEmail)}`)
            .then(response => {
              if (response.data.code === 0) {
                ElMessage.success('验证码已发送到邮箱');
                this.startCountdown();
              } else {
                ElMessage.error(response.data.message);
              }
            })
            .catch(() => {
              ElMessage.error('发送验证码失败');
            });
      }
    },
    startCountdown() {
      this.isButtonDisabled = true;
      this.countdown = 60;
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(timer);
          this.isButtonDisabled = false;
        }
      }, 1000);
    },
    onSubmit() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          const fullEmail = `${this.registerForm.emailPrefix}@163.com`;
          axios.post('/user/register', new URLSearchParams({
            username: this.registerForm.username,
            password: this.registerForm.password,
            email: fullEmail,
            verificationCode: this.registerForm.verificationCode
          }))
              .then(response => {
                if (response.data.code === 0) {
                  ElMessage.success('注册成功，请检查邮箱以完成验证');
                  this.$router.push('/login');
                } else {
                  ElMessage.error(response.data.message);
                }
              })
              .catch(() => {
                ElMessage.error('注册失败');
              });
        } else {
          ElMessage.error('请正确填写表单');
          return false;
        }
      });
    },
    goToLogin() {
      this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.input-field {
  width: 100%;
}

.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('@/assets/background.jpg') no-repeat center center;
  background-size: cover;
}

.register-form {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.register-form h2 {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-weight: bold;
  font-size: 24px;
}

.verification-container {
  display: flex;
  align-items: center;
}

.verification-input {
  flex: 1;
}

.send-code-button {
  margin-left: 10px;
}

.button-row {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.register-button,
.login-button {
  width: calc(100% / 3);
  max-width: 120px;
  border-radius: 8px;
  padding: 10px;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
}

.register-button {
  background-color: #47cf2d;
  color: #fff;
  margin-left: 85px;
}

.login-button {
  background-color: #2dcbcc;
  color: #fff;
}
</style>
